package com.zzyl.framework.interceptor;

import cn.hutool.core.util.StrUtil;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.framework.web.service.TokenService;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * TODO
 *
 * @Author xiqi
 */
@Component
public class MemberInterceptor implements HandlerInterceptor {
    @Autowired
    private TokenService tokenService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.如果不是controller资源，直接放行
        if(!(handler instanceof HandlerMethod)){
            return true;
        }
        //2.获取请求头的token
        String token = request.getHeader(HttpHeaders.PROXY_AUTHORIZATION);
        
        //3.判断请求头中的token是否为空
        if (StrUtil.isBlank(token)) {
            //为空返回401
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
        try {
            //4.不为空验证令牌
            Claims claims = tokenService.parseToken(token);
            //5.将令牌中的数据保存到ThreadLocal
            Long userId = Long.valueOf(claims.get("userId").toString());
            UserThreadLocal.set(userId);
            return true;
        } catch (Exception e) {
         e.printStackTrace();
         response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
         return false;
        }
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocal.remove();
    }


}
